#! /usr/bin/env bash

# 编译x264

set -e

# 当前执行脚本所在的文件夹
SCRIPT_DIR=$(cd "$(dirname "$0")";
pwd)

TARGET=$1
SOURCE_REPO=$2
BUILD_PATH=${BUILD_DIR}/android
OUTPUT=${BUILD_PATH}/x264-${TARGET}
TOOLCHAIN_PATH=${BUILD_PATH}/toolchains/x264-${TARGET}

cd ${SOURCE_REPO}

# 检测环境属性
. tools/do-detect-env.sh

# 目标平台
TARGET_API=${NDK_MIN_API}
# 配置参数
CFG_FLAGS=
# Standard options
EXTRA_CFLAGS=
EXTEA_LDFLAGS=

CROSS_PREFIX=
HOST=
TOOLCHAIN_NAME=

# 根据生成目标配置参数
case ${TARGET} in

    armv5)
        CROSS_PREFIX="arm-linux-androideabi"
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_VER}
        HOST="arm-linux-androideabi"
    ;;

    armv7a)
        CROSS_PREFIX="arm-linux-androideabi"
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_VER}
        HOST="arm-linux-androideabi"
    ;;

    arm64)
    # android-21或以上平台才支持64位
        TARGET_API=21
        CROSS_PREFIX="aarch64-linux-android"
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_64_VER}
        HOST="aarch64-linux"
    ;;

    x86)
        CROSS_PREFIX="i686-linux-android"
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_VER}
        HOST="i686-linux"
    ;;

    x86_64)
    # android-21或以上平台才支持64位
        TARGET_API=21
        CROSS_PREFIX="x86_64-linux-android"
        TOOLCHAIN_NAME=${CROSS_PREFIX}-${NDK_GCC_64_VER}
        HOST="x86_64-linux"
    ;;

    *)
        echo "openh264: 不支持编译'$TARGET'目标"
        exit 1
    ;;

esac

# make standalone toolchain
${ANDROID_NDK}/build/tools/make-standalone-toolchain.sh  \
 --platform=android-${TARGET_API}  \
 --toolchain=${TOOLCHAIN_NAME}  \
 --install-dir=${TOOLCHAIN_PATH}

SYSROOT=${TOOLCHAIN_PATH}/sysroot

export PATH=${TOOLCHAIN_PATH}/bin/:$PATH

CFG_FLAGS="$CFG_FLAGS --prefix=$OUTPUT --host=$HOST --enable-static --enable-pic --disable-cli "
CFG_FLAGS="$CFG_FLAGS --cross-prefix=${CROSS_PREFIX}- --sysroot=$SYSROOT --extra-cflags=$EXTRA_CFLAGS --extra-ldflags=$EXTEA_LDFLAGS"

# configure
echo CFG_FLAGS=${CFG_FLAGS}
./configure ${CFG_FLAGS}

# compile
make depend
make -j
make install